package com.aiyan.edu.framework.canary.context;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableDefault;

/**
 * Hystrix隔离下的灰度标签上下文传递
 *
 * @author: zqzhou
 * @create: 2019/12/05 09:39
 **/
public class CanaryContextHolder {

    public static final String CANARY_META_KEY = "canary";
    public static final String CANARY_META_VALUE = "gray";

    private static final HystrixRequestVariableDefault<String> context = new HystrixRequestVariableDefault<>();

    public static String getCanaryContext() {
        initCanaryContext();
        return context.get();
    }

    public static void setCanaryContext(String value) {
        initCanaryContext();
        context.set(value);
    }

    private static void initCanaryContext() {
        if (!HystrixRequestContext.isCurrentThreadInitialized()) {
            HystrixRequestContext.initializeContext();
        }
    }

    public static void destroy() {
        if (HystrixRequestContext.isCurrentThreadInitialized()) {
            HystrixRequestContext.getContextForCurrentThread().shutdown();
        }
    }
}
